package com.locationtracker.plus.ui.fragment.mine

import android.os.Bundle
import androidx.core.os.bundleOf
import com.locationtracker.plus.R
import com.locationtracker.plus.app.appViewModel
import com.locationtracker.plus.app.base.BaseFragment
import com.locationtracker.plus.app.eventViewModel
import com.locationtracker.plus.app.ext.jumpBySubscribe
import com.locationtracker.plus.app.ext.showMessage
import com.locationtracker.plus.app.network.NetworkApi
import com.locationtracker.plus.app.util.CacheUtil
import com.locationtracker.plus.databinding.FragmentMineBinding
import com.locationtracker.plus.viewmodel.state.LoginRegisterViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

class MineFragment : BaseFragment<LoginRegisterViewModel, FragmentMineBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        appViewModel.userInfo.value?.let {
            mViewModel.userInfo.set(it)
        }
        mDatabind.includeHeader.headerBack.setOnClickListener { nav().navigateUp() }
        mDatabind.vm = mViewModel

        mDatabind.click = ProxyClick()
    }

    override fun createObserver() {
        eventViewModel.loginEvent.observeInFragment(this) {
            appViewModel.userInfo.value?.let {
                mViewModel.userInfo.set(it)
            }
        }
    }

    inner class ProxyClick {
        fun login() {
            nav().jumpBySubscribe()
        }

        fun logout() {
            showMessage(
                "Are you sure to logout now",
                positiveButtonText = "Logout",
                negativeButtonText = "Cancel",
                positiveAction = {
                    //清空cookie
                    NetworkApi.INSTANCE.cookieJar.clear()
                    CacheUtil.setUser(null)
                    appViewModel.userInfo.value = null
                    eventViewModel.loginEvent.value = false
                    mViewModel.userInfo.set(null)
                })
        }

        fun agreementUser() {
            nav().navigateAction(
                R.id.action_to_webFragment,
                bundleOf("url" to "https://kdocs.cn/l/cg1uOJLTlx5O")
            )
        }

        fun agreementPrivacy() {
            nav().navigateAction(
                R.id.action_to_webFragment,
                bundleOf("url" to "https://kdocs.cn/l/cdq62si0A72i")
            )
        }

        fun tutorial() {
            nav().navigateAction(R.id.action_to_tutorialFragment)
        }
    }
}